package cn.iocoder.yudao.module.pay.splitting.dao;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.mapper.CoreMapper;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.module.api.pay.splitting.enums.MallBookSplitStatusEnum;
import cn.iocoder.yudao.module.pay.splitting.convert.PaySplittingConvert;
import cn.iocoder.yudao.module.pay.splitting.pojo.po.PaySplitting;
import cn.iocoder.yudao.module.pay.splitting.pojo.vo.MallBookSplittingVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * Mapper 接口
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/07/22
 */
@Mapper
public interface PaySplittingMapper extends CoreMapper<PaySplitting> {

    default List<PaySplitting> selectByMinDateTimeAndCanReceived(LocalDateTime minDateTime) {
        List<PaySplitting> list = selectList(new LambdaQueryWrapper<PaySplitting>()
                .eq(PaySplitting::getStatus, MallBookSplitStatusEnum.SUCCESS.getValue())
                .eq(PaySplitting::getReceived, false)
                .ge(PaySplitting::getCreateTime, minDateTime));
        if (CollUtil.isEmpty(list)) {
            return List.of();
        }
        return list;
    }

    default void saveSyncResult(String payNo, Long splitAmount, String splitUserId, MallBookSplittingVO result) {
        CoreLambdaQueryWrapper<PaySplitting> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(PaySplitting::getPayNo, payNo);
        PaySplitting shipping = selectOne(wrapper);
        if (shipping == null) {
            shipping = PaySplittingConvert.INSTANCE.convert(payNo, splitAmount, splitUserId, result);
            insert(shipping);
        } else {
            PaySplitting updateObj = PaySplittingConvert.INSTANCE.convert(payNo, splitAmount, splitUserId, result);
            updateObj.setId(shipping.getId());
            updateById(updateObj);
        }
    }

    default void updateResult(String payNo, MallBookSplittingVO result) {
        PaySplitting updateObj = PaySplittingConvert.INSTANCE.convert(payNo, null, null, result);
        update(updateObj, new LambdaUpdateWrapper<PaySplitting>().eq(PaySplitting::getPayNo, payNo));
    }

    default void updateReceived(String payNo, boolean success) {
        PaySplitting updateObj = new PaySplitting();
        updateObj.setReceived(success);
        update(updateObj, new LambdaUpdateWrapper<PaySplitting>()
                .eq(PaySplitting::getPayNo, payNo)
                .eq(PaySplitting::getReceived, false));
    }

}
